/* ***** BEGIN LICENSE BLOCK *****
 *   Version: MPL 1.1/GPL 2.0/LGPL 2.1
 *
 * The contents of this file are subject to the Mozilla Public License Version
 * 1.1 (the "License"); you may not use this file except in compliance with
 * the License. You may obtain a copy of the License at
 * http://www.mozilla.org/MPL/
 * 
 * Software distributed under the License is distributed on an "AS IS" basis,
 * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
 * for the specific language governing rights and limitations under the
 * License.
 *
 * The Original Code is ThumbsDown.
 *
 * The Initial Developer of the Original Code is
 * Atte Kemppilä.
 * Portions created by the Initial Developer are Copyright (C) 2007
 * the Initial Developer. All Rights Reserved.
 *
 * Contributor(s):
 *
 * Alternatively, the contents of this file may be used under the terms of
 * either the GNU General Public License Version 2 or later (the "GPL"), or
 * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
 * in which case the provisions of the GPL or the LGPL are applicable instead
 * of those above. If you wish to allow use of your version of this file only
 * under the terms of either the GPL or the LGPL, and not to allow others to
 * use your version of this file under the terms of the MPL, indicate your
 * decision by deleting the provisions above and replace them with the notice
 * and other provisions required by the GPL or the LGPL. If you do not delete
 * the provisions above, a recipient may use your version of this file under
 * the terms of any one of the MPL, the GPL or the LGPL.
 * 
 * ***** END LICENSE BLOCK ***** */


const Cc = Components.classes;
const Ci = Components.interfaces;
const Cu = Components.utils;

Cu.import("resource://gre/modules/Services.jsm");
Cu.import("resource://gre/modules/XPCOMUtils.jsm");

Cu.import("resource://thumbsdown/ScriptRunner.jsm");
Cu.import("resource://thumbsdown/ThumbsDown.jsm");
Cu.import("resource://thumbsdown/util.jsm");

const STRING_BUNDLE_URI = "chrome://thumbsdown/locale/scriptrunner.properties";

const TOPIC_NEW     = "thumbsdown-script-new";
const TOPIC_DESTROY = "thumbsdown-script-destroy";
const TOPIC_CHANGE  = "thumbsdown-script-change";

const EVENT_HANDLERS = {}
EVENT_HANDLERS[TOPIC_NEW]     = onScriptNew;
EVENT_HANDLERS[TOPIC_DESTROY] = onScriptDestroy;
EVENT_HANDLERS[TOPIC_CHANGE]  = onScriptChange;

var _;
var scriptRunner = ScriptRunner;
var tree;
var observer;
var isContextMenuOpen = false;
var updateTimer;


function onLoad()
{
    _ = getStringBundleGetter(Services.strings.createBundle(STRING_BUNDLE_URI));
    tree = document.getElementById("tree_scripts");
    tree.view = new ScriptRunnerTreeView(scriptRunner);
    observer = new ScriptRunnerObserver();
    
    // update timer
    var updateDelay = ThumbsDown.prefs.getIntPref("scriptrunner.updateDelay");
    if (updateDelay > 0)
    {   
        updateTimer = new Timer(false, updateDelay, null, onUpdateTimer);
        updateTimer.start();
    }
    
    let controller = new Controller(tree.view);
    window.controllers.insertControllerAt(0, controller);
    
    // init ui
    _update();
}

function onUnload()
{
    observer.unregister();
    if (updateTimer)
        updateTimer.stop();
}

function onUpdateTimer()
{
    var col = tree.columns["tcol_elapsed"];
    tree.treeBoxObject.invalidateColumn(col);
}

function onTreeSelect()
{
    window.updateCommands("tree-select");
}

function onTooltipShowing(e)
{
    if (isContextMenuOpen)
        return false;
    var row = _getTreeRowAt(e.clientX, e.clientY);
    if (row == -1)
        return false;
    var script = scriptRunner.scripts[row];
    document.getElementById("row_thumbnail").hidden = script.parent;
    document.getElementById("row_link").hidden = script.parent;
    for each (var name in ["name", "status", "elapsed", "document",  "thumbnail", "link", "image"])
        if (! document.getElementById("row_" + name).hidden)
            document.getElementById("descr_" + name).value = _getScriptPropertyAsText(script, name);
    document.getElementById("thumbnail").src = (script.parent ? script.parent.thumbnailUrl : script.thumbnailUrl);
    return true;
}

function onTooltipHidden()
{
    document.getElementById("thumbnail").src = "";
}

function onContextMenuShowing(e)
{
    isContextMenuOpen = true;
    return true;
}

function onContextMenuHidden()
{
    isContextMenuOpen = false;
}

function onScriptNew(scriptRunner, oldLength)
{
    oldLength = Number(oldLength);
    var count = scriptRunner.length - oldLength;
    tree.treeBoxObject.rowCountChanged(oldLength, count);
    updateTimer.trigger();
    schedule(null, _update);
}

function onScriptDestroy(scriptRunner, indexes)
{
    indexes = JSON.parse(indexes);
    var selection = tree.view.selection;
    selection.selectEventsSuppressed = true;
    tree.treeBoxObject.beginUpdateBatch();
    for each (var index in indexes)
        tree.treeBoxObject.rowCountChanged(index, -1);
    tree.treeBoxObject.endUpdateBatch();
    selection.selectEventsSuppressed = false;
    updateTimer.trigger();
    schedule(null, _update);
}

function onScriptChange(script)
{
    tree.treeBoxObject.invalidateRow(script.index);
    if (script.parent && (script.parent.index != undefined))
        tree.treeBoxObject.invalidateRow(script.parent.index);
    
    if (script.isError && ThumbsDown.prefs.getBoolPref("scriptrunner.attention"))
        window.getAttention();
    
    updateTimer.trigger();
    schedule(null, _update);
}

function startScript()
{
    var script = _getSelectedScript();
    if (script)
        script.start();
}

function stopScript()
{
    var scriptIterator = _getSelectedScriptIterator();
    var scripts = [script for each (script in scriptIterator)];
    for each (var script in scripts)
        if (script.isRunning)
            script.cancel();
}

function removeScript()
{
    var scriptIterator = _getSelectedScriptIterator();
    var scripts = [script for each (script in scriptIterator)];
    for each (var script in scripts)
        if (script.isRunning)
            return;
    var indexes = [script.index for each (script in scripts)];
    scriptRunner.removeScripts(indexes);
}

function removeCompleted()
{
    let indexes = [script.index for each (script in scriptRunner.scripts) if (script.isSuccess)];
    scriptRunner.removeScripts(indexes);
}

function selectAll()
{
    tree.view.selection.selectAll();
}

function deselectAll()
{
    tree.view.selection.clearSelection();
}

function openScript()
{
    var script = _getSelectedScript();
    if (! script)
        return;
    
    // TODO: don't open dialog if script doesn't exist
    ThumbsDown.openScriptDialog("set", script.scriptId);
}

function openDocument()
{
    let urls = [script.documentUrl for each (script in _getSelectedScriptIterator())];
    openUrls(unique(urls));
}

function openLink()
{
    let urls = [script.linkUrl for each (script in _getSelectedScriptIterator())];
    openUrls(unique(urls));
}

function openPrefWindow()
{
    ThumbsDown.openPrefWindow();
}

function _getSelectedScript()
{
    var selection = tree.view.selection;
    if (selection.count != 1)
        return null;
    return scriptRunner.scripts[tree.currentIndex];
}

function _getSelectedScriptIterator()
{
    var selection = tree.view.selection;
    for each (var index in SelectionIterator(selection))
        yield scriptRunner.scripts[index];
}

function _getTreeRowAt(x, y)
{
    var row = {};
    var col = {};
    var childElement = {};
    tree.treeBoxObject.getCellAt(x, y, row, col, childElement);
    return row.value;
}

function _update()
{
    _updateTitle();
    goUpdateCommands();
}

function _updateTitle()
{
    let title =
        scriptRunner.count.success + 
        ":" + (scriptRunner.count.cancelled + scriptRunner.count.error) +
        "/" + scriptRunner.length +
        " - " + _("window.title");
    
    document.title = title;
}

function _getScriptPropertyAsText(script, name)
{
    switch (name)
    {
        case "name":      return script.name;
        case "status":    return _getStatus(script);
        case "elapsed":   return _getElapsed(script.startTime, script.endTime);
        case "document":  return script.documentUrl;
        case "thumbnail": return script.thumbnailUrl;
        case "link":      return (script.linkUrl ? script.linkUrl : "");
        // TODO: result is an array -> there can be multiple results
        case "image":     return (script.child ? (script.child.result ? script.child.result[0].url : "") : (script.result ? script.result[0].url : ""));
        default:
            throw new Error("unknown name: " + name);
    }
}

function _getStatus(script)
{
    switch (script.state)
    {
       case 0: return _("status.queued");
       case 1: return _("status.evaluating", script.scriptState);
       case 2: return _("status.loading", script.scriptState);
       case 3: return _("status.callback");
       case 4: return _("status.cancelled");
       case 5: return _("status.success") + (script.child ? " > " + _getStatus(script.child) : "");
       case 6:
           var oldStatus = this._getStatus({state: script.oldState, scriptState: script.scriptState});
           return _("status.error", oldStatus, script.error);
       default:
           throw new Error("invalid state:" + script.state);
    }
}

function _getElapsed(start, end)
{
    if (! start)
        return null;
    start = start.getTime();
    end = (end ? end.getTime() : Date.now());
    var time = "" + Math.round((end - start) / 100);
    if (time.length == 1)
        return "0." + time + "s";
    var i = time.length - 1;
    return time.substr(0, i) + "." + time.charAt(i) + "s";
}


function goUpdateCommands()
{
    for each (let command in Controller.prototype.commands)
        goUpdateCommand(command);
}


// nsIController
function Controller(treeView)
{
    this.treeView = treeView;
    this.selection = treeView.selection;
}

Controller.prototype =
{
    commands:
    [
        "cmd_startScript",
        "cmd_stopScript",
        "cmd_removeScript",
        "cmd_removeCompleted",
        "cmd_openPrefWindow",
        "cmd_selectAll",
        "cmd_deselectAll",
        "cmd_openScript",
        "cmd_openDocument",
        "cmd_openLink",
    ],
    
    supportsCommand: function(command)
    {
        return (this.commands.indexOf(command) != -1);
    },
    
    isCommandEnabled: function(command)
    {
        switch (command)
        {
            case "cmd_deselectAll":
            case "cmd_openPrefWindow":
            case "cmd_removeCompleted":
            case "cmd_selectAll":
                return true;
            case "cmd_openScript":
                return (this.selection.count == 1);
            case "cmd_openDocument":
            case "cmd_openLink":
                return (this.selection.count > 0);
            case "cmd_startScript":
            case "cmd_stopScript":
            case "cmd_removeScript":
                return this._isScriptCommandEnabled(command);
            default:
                throw new Error("unknown command: " + command);
        }
    },
    
    _isScriptCommandEnabled: function(command)
    {
        switch (this.selection.count)
        {
            case 0:
                return false;
            case 1:
                switch (command)
                {
                    case "cmd_startScript":  return _getSelectedScript().isQueued;
                    case "cmd_stopScript":   return _getSelectedScript().isRunning;
                    case "cmd_removeScript": return (! _getSelectedScript().isRunning);
                    default: throw new Error("unknown command: " + command);
                }
            default:
                switch (command)
                {
                    case "cmd_startScript":  return false;
                    case "cmd_stopScript":   return ([s for each (s in _getSelectedScriptIterator()) if (s.isRunning)].length > 0);
                    case "cmd_removeScript": return ([s for each (s in _getSelectedScriptIterator()) if (s.isRunning)].length == 0);
                    default: throw new Error("unknown command: " + command);
                }
        }
    },
    
    doCommand: function(command)
    {
        if (this.isCommandEnabled(command))
            window[command.substr("cmd_".length)]();
    },
    
    onEvent: function(eventName)
    {
        // empty
    },
}


function ScriptRunnerObserver()
{
    this.register();
}

ScriptRunnerObserver.prototype =
{
    observe: function(subject, topic, data)
    {
        if (! (topic in EVENT_HANDLERS))
            throw new Error("unknown topic: " + topic);
        EVENT_HANDLERS[topic](subject.wrappedJSObject, data);
    },
    
    register: function()
    {
        for (var topic in EVENT_HANDLERS)
            Services.obs.addObserver(this, topic, false);
    },
    
    unregister: function()
    {
        for (var topic in EVENT_HANDLERS)
            Services.obs.removeObserver(this, topic);
    }
}


// TODO: cache cell texts? no direct access to underlying model
function ScriptRunnerTreeView(scriptRunner)
{
    this.scripts = scriptRunner.scripts;
}

ScriptRunnerTreeView.prototype =
{
    QueryInterface: XPCOMUtils.generateQI([Ci.nsITreeView]),
    
    // nsITreeView
    get rowCount() { return this.scripts.length; },
    
    setTree: function(treeBox)
    {
        this.treeBox = treeBox;
    },
    
    getCellText: function(row, col)
    {
        var index = col.id.lastIndexOf("_");
        var name = col.id.substr(index + 1);
        var script = this.scripts[row];
        return _getScriptPropertyAsText(script, name);
    },
    
    isContainer: function(row) { return false; },
    isSeparator: function(row) { return false; },
    isSorted: function() { return false; },
    getLevel: function(row) { return 0; },
    getImageSrc: function(row, col) { return null; },
    getRowProperties: function(row) { return ""; },
    getCellProperties: function(row, col) { return ""; },
    getColumnProperties: function(colid, col) { return ""; }
}
